package redis_test;

import redis.clients.jedis.Jedis;

public class String_ {
    static final long count = 100000;

    public static void main(String[] args) {
        //没用数据的时候 used_memory:1035360

        //添加100万个string的key value
        long base = 100_0000000;
        /*for (int i = 0; i < 10; i++) {
            long j = base;
            long count_ = count;
            Jedis jedis = new Jedis("localhost", 6379);
            new Thread(() -> {
                for (long s = j; s < j + count_; s++) {
                    jedis.set(s + "", (s + 100) + "");
                }
            }).start();
            base += count_;
        }
        //当前 89423360
        //计算得到，占用的内存为84mb
        System.out.println((89423360-1035360)*1.0/(1024*1024));*/

        //通过hash的方式添加,flushall后的内存 1035600
        //修改参数 config set hash-max-ziplist-entries 1000
        //"hash-max-ziplist-value" 默认是"64" 不用修改

        for (int i = 0; i < 10; i++) {
            long j = base;
            long count_ = count;
            Jedis jedis = new Jedis("localhost", 6379);
            new Thread(() -> {
                for (long s = j; s < j + count_; s++) {
                    String s1 = s + "";
                    String s2 = (s + 100) + "";
                    String[] sub = sub(s1, s2, 3);
                    jedis.hset(sub[0], sub[1], sub[2]);
                }
            }).start();
            base += count_;
        }
        //此时内存11347872
        //计算得到，只用了9.83mb
        System.out.println((11347872-1035360)*1.0/(1024*1024));


        //综上，使用hash存储，比使用string存储，节约了将近80mb的内存！
    }

    public static String[] sub(String s1,String s2,int count){
        String res1=s1.substring(0,s1.length()-count);
        StringBuilder sb=new StringBuilder();
        for (int j=count;j>0;j--)
            sb.append(s1.charAt(s1.length()-j));
        //第一个返回值代表全局的key
        //第二个返回值代表hash表的key （最多1000个）
        //第三个返回值代表hash表的value
        return new String[]{res1,sb.toString(),s2};
    }

}
